package com.example.nacos.ribbon.controller;

import com.example.nacos.ribbon.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @ClassName : RibbonController
 * @Description : 测试ribbon的负载均衡
 * @Author : tianshuo
 * @Date: 2021-04-02 22:55
 */
@RestController
public class RibbonController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/ribbon/service")
    public List<ServiceInstance> service() {
        List<ServiceInstance> instances = discoveryClient.getInstances("nacos-provider");
        return instances;
    }

    @GetMapping("/ribbon/loadBalance/{id}")
    public Product loadBalance(@PathVariable("id") Integer id) {
        Product product = restTemplate.getForObject("http://nacos-provider/product/" + id, Product.class);
        return product;
    }

    /**
     * 获取的请求头
     * @param request
     * @return
     */
    @GetMapping("/ribbon/header")
    public String requestHeader(HttpServletRequest request) {
        String header = request.getHeader("X-Request-Id");
        return header;
    }


}

